package com.foreveross.crawl.adapter.sub.impl20140402.v3;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;

import com.foreveross.crawl.adapter.AbstractAdapter;
import com.foreveross.crawl.adapter.PlaneInfoEntityBuilder;
import com.foreveross.crawl.common.util.RegHtmlUtil;
import com.foreveross.crawl.domain.airfreight.AbstractPlaneInfoEntity;
import com.foreveross.crawl.domain.airfreight.CabinEntity;
import com.foreveross.crawl.domain.airfreight.doub.ReturnCabinEntity;
import com.foreveross.crawl.domain.airfreight.doub.ReturnDoublePlaneInfoEntity;
import com.foreveross.crawl.exception.FlightInfoNotFoundException;
import com.foreveross.taskservice.common.bean.TaskModel;
import com.google.common.collect.Maps;

public class KunmingAdapter extends AbstractAdapter {
	public KunmingAdapter(TaskModel taskQueue) {
		super(taskQueue);
		// TODO Auto-generated constructor stub
	}

	HttpClient client = null;


	@Override
	public List<Object> paraseToVo(Object fetchObject) throws Exception {
		if (fetchObject == null) {
			throw new FlightInfoNotFoundException("无该航班");
		}
		List list = (List) fetchObject;
		if (list.size() == 0) {
			throw new FlightInfoNotFoundException("无该航班");
		}
		return list;
	}

	@Override
	public String getUrl() throws Exception {
		return null;
	}

	private String getPageHtml() throws Exception {
		HttpRequestBase request = null;
		String html = null;
		for (int i = 0; i < 3; i++) {
			try {
				String flightType = this.taskQueue.getIsReturn() == 1 ? "WF" : "DC";
				String flightDates = this.taskQueue.getIsReturn() == 1 ? (taskQueue.getFlightDate() + ";" + taskQueue.getReturnGrabDate()) : taskQueue.getFlightDate();
				String url = "http://www.airkunming.com/booking/flightSearch?dstCity=" + taskQueue.getToCity() + "&flightDates=" + flightDates + "&flightType=" + flightType + "&orgCity=" + taskQueue.getFromCity();
				request = new HttpPost(url);
				html = super.excuteRequest(getHttpClient(), request, true);
				rollbackProxyIp(true);
				break;
			} catch (Exception e) {
				logger.error("数据获取错误：" + e.getMessage());
				rollbackProxyIp(false);
				switchProxyipByHttClient();
			}
		}

		if (html == null) {
			throw new Exception("抓取页面数据失败");
		}

		super.appendPageContents(html);
		super.setLenghtCount(super.getSourceWebPageContents().length());
		return html;
	}

	@Override
	public Object fetch(String url) throws Exception {
		List<AbstractPlaneInfoEntity> result = new ArrayList<AbstractPlaneInfoEntity>();
		String html = getPageHtml(); // 获取数据 ;

		List<List<String>> head = RegHtmlUtil.retrieveLinkss(html, getRegex3());
		if (head == null || head.size() == 0) {
			return new ArrayList();
		}
		List<String> cabinNames = RegHtmlUtil.retrieveLinks(head.get(0).get(0), getRegex4(), 1);
		cabinNames = cabinNames.subList(3, cabinNames.size() - 1);

		// 14/07/03 加上税费
		String jcjsfRegex = "机场建设费.*?</label>(.*?)</label>";
		String ryfjsRegex = "燃油附加税.*?</label>(.*?)</label>";
		List<String> jcjsList = null;
		List<String> ryfjList = null;
		try {
			jcjsList = RegHtmlUtil.retrieveLinks(html, jcjsfRegex, 1);
			ryfjList = RegHtmlUtil.retrieveLinks(html, ryfjsRegex, 1);
		} catch (Exception e) {
			logger.info("抓取税费失败");
			throw e;
		}
		Double taxesPrice = Double.valueOf(jcjsList.get(0)) + Double.valueOf(ryfjList.get(0));
		buildPlaneInfos(false, result, html, cabinNames, taskQueue.getFromCity(), taskQueue.getToCity(), taxesPrice);

		if (taskQueue.getIsReturn() != 1) {
			PlaneInfoEntityBuilder.buildLimitPrice(result);
			return result;
		}
		List returnResult = new ArrayList<AbstractPlaneInfoEntity>();

		taxesPrice = Double.valueOf(jcjsList.get(1)) + Double.valueOf(ryfjList.get(1));
		buildPlaneInfos(true, returnResult, html, cabinNames, taskQueue.getToCity(), taskQueue.getFromCity(), taxesPrice);
		for (AbstractPlaneInfoEntity from : result) {
			PlaneInfoEntityBuilder.getDoubleEntity(from).getReturnPlaneInfos().addAll(returnResult);
		}
		PlaneInfoEntityBuilder.buildRelation(result, returnResult);
		PlaneInfoEntityBuilder.buildLimitPrice(result);

		return result;
	}

	private void buildPlaneInfos(boolean isReturn, Collection<AbstractPlaneInfoEntity> result, String html, List<String> cabinNames, String from, String to, Double taxesPrice) throws Exception {
		List<List<String>> orgs = RegHtmlUtil.retrieveLinkss(html, getRegex1(from, to));// 已经展示的列表
		for (List<String> org : orgs) {
			AbstractPlaneInfoEntity planeInfo = null;
			if (isReturn) {
				planeInfo = PlaneInfoEntityBuilder.buildPlaneInfo(this.taskQueue, "KY", "昆航", "昆明航空", org.get(2), org.get(3), org.get(1), null, null, null, org.get(4), ReturnDoublePlaneInfoEntity.class);
			} else {
				planeInfo = PlaneInfoEntityBuilder.buildPlaneInfo(this.taskQueue, "KY", "昆航", "昆明航空", org.get(2), org.get(3), org.get(1), null, null, null, org.get(4));
			}
			result.add(planeInfo);
			List<String> showCabins = RegHtmlUtil.retrieveLinks(org.get(6), getRegex2(), 0);
			Map cabinMap = Maps.newHashMap();
			for (int i = 0; i < showCabins.size(); i++) {
				List<List<String>> cabins = RegHtmlUtil.retrieveLinkss(showCabins.get(i), this.getRegex6());
				if (cabins == null || cabins.size() == 0) {
					continue;
				} else {
					List<String> cabin = cabins.get(0);
					this.buildCabin(isReturn, cabinMap, planeInfo, cabinNames.get(i), cabin.get(1), cabinNames.get(i), PlaneInfoEntityBuilder.getDouble(cabin.get(2)), taxesPrice);
				}
			}
			List<List<String>> moreCabins = RegHtmlUtil.retrieveLinkss(org.get(7), getRegex7());
			for (List<String> otherCablin : moreCabins) {
				this.buildCabin(isReturn, cabinMap, planeInfo, otherCablin.get(2), otherCablin.get(1), otherCablin.get(2), PlaneInfoEntityBuilder.getDouble(otherCablin.get(3)), taxesPrice);
			}
			if (isReturn) {
				PlaneInfoEntityBuilder.getReturnDoubleEntity(planeInfo).getReturnCabins().addAll(cabinMap.values());
			} else {
				if (taskQueue.getIsReturn() != 1) {
					PlaneInfoEntityBuilder.getSingleEntity(planeInfo).getCabins().addAll(cabinMap.values());
				} else {
					PlaneInfoEntityBuilder.getDoubleEntity(planeInfo).getCabins().addAll(cabinMap.values());
				}
			}
		}
	}

	public void buildCabin(boolean isReturn, Map cabinMap, AbstractPlaneInfoEntity planeInfo, String cabinType, String subCabinName, String productName, Double price, Double taxesPrice) {
		if (isReturn) {
			ReturnCabinEntity cabinEntity = new ReturnCabinEntity();
			cabinEntity.setCabinType(cabinType);
			cabinEntity.setPlaneInfoEntity(planeInfo);
			cabinEntity.setPrice(price);
			cabinEntity.setProductName(productName);
			cabinEntity.setSubCabinName(subCabinName);
			cabinEntity.setTaxesPrice(taxesPrice);
			cabinEntity.setOriginalPrice(price + taxesPrice);
			cabinMap.put(price, cabinEntity);
		} else {
			CabinEntity cabinEntity = new CabinEntity();
			cabinEntity.setCabinType(cabinType);
			cabinEntity.setPlaneInfoEntity(planeInfo);
			cabinEntity.setPrice(price);
			cabinEntity.setProductName(productName);
			cabinEntity.setSubCabinName(subCabinName);
			cabinEntity.setTaxesPrice(taxesPrice);
			cabinEntity.setOriginalPrice(price + taxesPrice);
			cabinMap.put(price, cabinEntity);
		}
	}

	@Override
	public boolean validateFetch(Object fetchObject) throws Exception {
		// TODO Auto-generated method stub
		return true;
	}

	public String getRegex1(String from, String to) {
		String regex = "class=\"tablex9 yuding_hb\" name=\"segment" + from + to + "\".+?<li class=\"liax10\"><div.+?>(.+?)</div>.+?";// 航班号
		regex += "<li class=\"liax10\">.*?<div.*?>.*?<label>.+?<label>(.+?)</label>.+?<label>.+?<label>(.+?)</label>.+?";// 开始时间 到达时间
		regex += "<li.+?<label>.+?<label>(.+?)</label>.+?<label>.+?<label>(.+?)</label>";// 飞机型号，中转站
		regex += "(.+?)onclick=\"showMoreClasses.+?</li>.+?</li>(.+?)</div>\\s*?</div>\\s*?</div>\\s*?</div>\\s*?</div>";
		return regex;
	}

	public String getRegex2() {
		String regex = "<li class=\"liax10\".+?</li>";
		return regex;
	}

	public String getRegex6() {
		String regex = "value=\"(.+?);(.+?)\\*.+?\"";
		return regex;
	}

	public String getRegex5() {
		String regex = "moreClassesDiv";
		return regex;
	}

	public String getRegex3() {
		String regex = "<div class=\"tablex9 yuding_hb\" style.+?>(.+?</li>)\\s*?</div>";
		return regex;
	}

	public String getRegex4() {
		String regex = "<li class=\"liax9\".+?<div.*?>(.+?)</div></li>";
		return regex;
	}

	public String getRegex7() {
		String regex = "<li class=\"liax10\"[^\r]+?><div[^\r]+?>([^\\s]+?)<br>\\(([^\r]+?)\\)</div></li><li[^\r]+?><div[^\r]+?<input[^\r]+?>([^\r]+?)</div>";
		return regex;
	}
}
